package cn.faster.sys.service.impl;

import cn.faster.sys.entity.*;
import cn.faster.sys.mapper.SysMenuMapper;
import cn.faster.sys.mapper.SysRoleMapper;
import cn.faster.sys.mapper.SysRoleMenuCenterMapper;
import cn.faster.sys.mapper.SysUserRoleCenterMapper;
import cn.faster.sys.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * 用户权限表 服务实现类
 * </p>
 *
 * @author xiaoCoder
 * @since 2021-06-10
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    private final StringRedisTemplate redisTemplate;

    private final SysRoleMenuCenterMapper sysRoleMenuCenterMapper;

    private final SysRoleMapper sysRoleMapper;

    private final SysUserRoleCenterMapper sysUserRoleCenterMapper;

    private final SysMenuMapper sysMenuMapper;

    /**
     * 根据id查询Menu
     */
    @Override
    public SysMenu getMenuById(Long id) throws Exception {
        return sysMenuMapper.getMenuById(id);
    }

    /**
     * 查询Menu列表
     */
    @Override
    public List<SysMenu> listMenu(Map<String, Object> map) throws Exception {
        return sysMenuMapper.listMenu(map);
    }

    /**
     * 新增Menu
     */
    @Override
    @Transactional
    public Integer addMenu(SysMenu sysMenu) throws Exception {
        return sysMenuMapper.addMenu(sysMenu);
    }

    /**
     * 更新Menu
     */
    @Override
    @Transactional
    public Integer updateMenu(SysMenu sysMenu) throws Exception {
        return sysMenuMapper.updateMenu(sysMenu);
    }

    /**
     * 根据id删除Menu
     */
    @Override
    @Transactional
    public Integer deleteMenuById(Integer id) throws Exception {
        return sysMenuMapper.deleteMenuById(id);
    }

    /**
     * 根据id逻辑删除Menu
     */
    @Override
    @Transactional
    public Integer removeMenuById(Integer id) throws Exception {
        return sysMenuMapper.removeMenuById(id);
    }

    @Override
    public List<SysMenu> listWithTree() {
        // 1、查询所有 parentId 为 0 的数据
        List<SysMenu> sysMenus = baseMapper.selectList(new QueryWrapper<SysMenu>().eq("parent_id", 0L));
        // 2、查询其下面所有的数据信息
        extracted(sysMenus);
        return sysMenus;
    }

    private void extracted(List<SysMenu> sysMenus) {
        for (SysMenu sysMenu : sysMenus) {
            List<SysMenu> sysMenus1 = baseMapper.selectList(new QueryWrapper<SysMenu>().eq("parent_id", sysMenu.getId()));
            if (sysMenus1.size() == 0){
                continue;
            }
            sysMenu.setList(sysMenus1);
            extracted(sysMenus1);
        }
    }

}
